import time

import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

@pytest.fixture(scope="module")
def driver(request):
    driver = webdriver.Chrome()
    driver.implicitly_wait(5)
    yield driver
    driver.quit()


def test_search_automation(driver):
    text = "关键字"
    wait = WebDriverWait(driver, 10)
    # 访问必应搜索：https://cn.bing.com/?mkt=zh-CN
    driver.get("https://cn.bing.com/?mkt=zh-CN")
    # 点击搜索按钮，输入关键字
    wait.until(
        EC.element_to_be_clickable((By.CSS_SELECTOR, "#sb_form_c #sb_form_q"))
    ).send_keys(text)
    # 点击搜索按钮
    wait.until(
        EC.element_to_be_clickable((By.CSS_SELECTOR,"#search_icon"))
    ).click()
    # 获取当前句柄
    current = driver.current_window_handle
    # 点击第一个标题
    wait.until(
        EC.element_to_be_clickable((By.XPATH, "//a[contains(text(),'关键字（搜索引擎用语）_百度百科')]"))
    ).click()
    # 切换窗口
    wait.until(EC.number_of_windows_to_be(2))
    all_windows = driver.window_handles
    for window in all_windows:
        if current != window:
            driver.switch_to.window(window)
            break
    # 断言标题
    assert text in wait.until(
        EC.visibility_of_element_located((By.XPATH,"//h1[contains(text(),'关键字')]"))
    ).text